package com.learn.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 创建线程方式三：实现Callable接口
 *
 * 1.创建Callable实现类
 * 2.实现call方法，将此线程需要执行的操作声明在call()中
 * 3.创建接口实现类的对象
 * 4.将Callable接口实现类的对象作为参数传入FutureTask构造器中，创建FutureTask对象
 * 5.将FutureTask对象传入Thread类的构造器，创建Thread对象并调用start()
 */
class  NumThread implements Callable{
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(i);
                sum += i;
            }
        }

        return sum;
    }
}

public class ThreadCreatebByCallable {
    public static void main(String[] args) {
        NumThread t = new NumThread();

        FutureTask futureTask = new FutureTask(t);

        Thread thread = new Thread(futureTask);

        thread.start();

        try {
            //get()的返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值
            Object sum = futureTask.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
